# sterea.cs.umn.edu
# module load soft/mysql
# module load soft/ruby

require 'rubygems'
require "rexml/document"
require "open-uri"
require "cgi"
require 'digest/md5'


#FROB="72157625041849233-4001e662442717ab-54819442"
API_SECRET = "2a0184a18c05da51"
API_KEY = "c3cc36c3df04978a006e8437fba43b68"
AUTH_TOKEN="72157625166483106-c6be3928c6cc4923"
MIN_PER_PAGE="1"
MAX_PER_PAGE="500"
RECONNECT_INTERVAL = 30
FORCE_CONNECT = 1

def log(message, init=0)
	#puts message 
	$log_file.write("::#{Time.now}:: " + message.to_s+ "\n")
	$log_file.flush
end

def encode(str)
  return str if str == "" || str == nil
  return str.gsub(/\'/, "\\\\'")
end

def request(args={}, isMin=false)
  begin
    endpoint = "http://api.flickr.com/services/rest/"
    args["api_key"]=API_KEY
    args["auth_token"]=AUTH_TOKEN
    args["api_sig"]=api_sig(args)
    arg_map = args.collect {|arg,value| CGI.escape(arg)+"="+CGI.escape(value.to_s)}.join("&")
    call_uri = "#{endpoint}?#{arg_map}"
    response = REXML::Document.new(open(call_uri).read)
    if response.root.attributes["stat"] == "ok" then
      return response
    elsif response.root.attributes["stat"] == "fail" then
      raise "Flickr API error #{response.elements["rsp/err"].attributes["code"]}: #{response.elements["rsp/err"].attributes["msg"]}"
    else
      raise "Request status neither ok nor fail. Tried to fetch #{call_uri}."
    end
  rescue
    log($!.to_s)
    return nil
  end
end

def api_sig(args)
  signature=API_SECRET+args.sort.collect{|k,v| k+v}.join("")
  digest = Digest::MD5.hexdigest(signature)
end

def get_frob(args={})
  endpoint="http://flickr.com/services/auth/"
  args["api_sig"]=api_sig(args)
  arg_map = args.collect {|arg,value| CGI.escape(arg)+"="+CGI.escape(value.to_s)}.join("&")
  call_uri = "#{endpoint}?#{arg_map}"
end

def end_response
  $response += "</ol></div>"
end

def start_response
  $response = "<div class='carousel' id='container'><ol>"
end

def get_photo_url(photo_id)
  photo_sizes = []
  resp = request({"method"=>"flickr.photos.getSizes", "photo_id"=>photo_id})
  if resp != nil
    resp.elements.each("*/sizes/size") do |size| 
      photo_sizes << size.attribute("source").to_s
    end
  else 
    log($!)
    raise "Null response error"
  end 
  $response += "<li><a href='#{photo_sizes[3]}' target='_blank'><img src='#{photo_sizes[0]}'></a></li>"
end

def get_photos(tags)
  start_response
  resp = request({"method"=>"flickr.photos.search", "tags"=>CGI.escape(tags), "per_page"=>"20"})
  if resp != nil
    resp.elements.each("*/photos/photo") do |photo_info|
      next if photo_info.attribute("id") == nil
      get_photo_url(photo_info.attribute("id").to_s)
    end
  else 
    raise "Null response error"
  end
  end_response
  puts $response
end

def daemonize()
	exit if fork                   # Parent exits, child continues.
	Process.setsid                 # Become session leader.
	exit if fork                   # Zap session leader. 
end

#Control start point
unless ARGV.length == 1
  puts "Dude, not the right number of arguments."
  puts "Usage: ruby GetPhotos.rb <tag> \n"
  exit
end

#daemonize()
$log_file = File.open("flickr_photo_puller.log", "a+")
$debug = true
$response = ""


#Get photos by tag name
begin
  get_photos(ARGV[0])
rescue
  log $!.to_s
  log "Flickr down! Flickr down!"
end
$log_file.close()

# akshay
# 9986635977
